﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
using ZBJF.Warranty.BLL;
using ZBJF.Warranty.Common.Common;
using ZBJF.Warranty.Common.Enums.System;
using ZBJF.Warranty.Model;
using ZBJF.Warranty.Model.ViewModel.Product;
using ZBJF.Warranty.WebProvider;

namespace ZBJF.Warranty.AdminSite.Controllers
{
    public class AccessoriesTypeController : BaseController
    {
        #region 配件类型管理页面 + ActionResult AccessoriesTypeManage()
        /// <summary>
        /// 配件类型管理页面
        /// </summary>
        /// <returns></returns>
        public ActionResult AccessoriesTypeManage()
        {
            return View();
        }
        #endregion

        #region 配件类型管理页面获取列表数据 + ActionResult AccessoriesTypeList(AccessoriesTypeModel model)
        /// <summary>
        /// 配件类型管理页面获取列表数据
        /// </summary>
        /// <returns></returns>
        public ActionResult AccessoriesTypeList(AccessoriesTypeModel model)
        {
            var total = 0;
            var list = ServiceFactory.AccessoriesTypeServiceInstance.GetPagingList(model, out total).AsNoTracking().ToList().Select(o => new
            {
                o.ID,
                o.AccessoriesName,
                o.IsAvailable,
                LastModifyTime = o.LastModifyTime.ToString("yyyy-MM-dd HH:mm:ss"),
                o.LastModifyBy,
                ProductName = o.ProductType.ProductName,
                o.AccessoriesCode
            });
            return Json(new
            {
                sEcho = model.sEcho,
                iTotalRecords = total,
                iTotalDisplayRecords = total,
                aaData = list
            }, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 配件类型编辑 + ActionResult AccessoriesTypeEdit(int id)
        /// <summary>
        /// 配件类型编辑
        /// </summary>
        /// <returns></returns>
        public ActionResult AccessoriesTypeEdit(int id)
        {
            ViewBag.ShowTitle = id > 0 ? "编辑配件类型" : "添加配件类型";
            var accessoriesType = ServiceFactory.AccessoriesTypeServiceInstance.LoadByID(id);
            return View(accessoriesType);
        }

        #endregion

        #region 保存配件类型 + ActionResult SaveAccessoriesType(AccessoriesType model)

        [HttpPost]
        [ValidateInput(false)]
        //保存配件类型
        public ActionResult SaveAccessoriesType(AccessoriesType model)
        {
            var responseResult = new ResponseResult
            {
                OpreateType = model.ID > 0 ? OpreateType.Update : OpreateType.Add
            };

            var serv = ServiceFactory.AccessoriesTypeServiceInstance;
            model.AccessoriesName = model.AccessoriesName.Trim();
            if (model.ID == 0)
            {
                if (serv.IsExist(model.AccessoriesName))
                {
                    responseResult.Message = "该配件类型已经存在";
                    TempData["ResponseResult"] = responseResult;
                    return RedirectToAction("AccessoriesTypeEdit", new { id = model.ID });
                }
                model.CreateTime = DateTime.Now;
                model.CreateBy = CurrentUser.UserAccount;
                model.LastModifyBy = CurrentUser.UserAccount;
                model.LastModifyTime = DateTime.Now;
                using (TransactionScope ts = new TransactionScope())
                {
                    var entity = serv.AddEntities(model);
                    responseResult.Success = entity.ID > 0;
                    if (!responseResult.Success)
                    {
                        ts.Dispose();
                        TempData["ResponseResult"] = responseResult;
                        return RedirectToAction("AccessoriesTypeEdit", new { id = model.ID });
                    }
                    //设置编码
                    entity.AccessoriesCode = CommonMethod.GenerateCode("PJLX", entity.ID.ToString(), 6);
                    if (!serv.UpdateEntities(entity))
                    {
                        ts.Dispose();
                        responseResult.Message = "操作失败！设置配件类型编码失败";
                        TempData["ResponseResult"] = responseResult;
                        return RedirectToAction("AccessoriesLevelEdit", new { id = model.ID });
                    }
                    ts.Complete();
                }
            }
            else
            {
                var entity = serv.LoadByID(model.ID);
                if (entity != null)
                {
                    if (entity.AccessoriesName != model.AccessoriesName && serv.IsExist(model.AccessoriesName, model.ID))
                    {
                        responseResult.Message = "已存在同名的配件类型，请修改配件类型名称";
                    }
                    //entity = ReflectHelper<AccessoriesType, AccessoriesType>.CloneT1ToT2(model, entity);
                    entity.ProductTypeID = model.ProductTypeID;
                    entity.AccessoriesName = model.AccessoriesName;
                    entity.IsAvailable = model.IsAvailable;
                    entity.LastModifyBy = CurrentUser.UserAccount;
                    entity.LastModifyTime = DateTime.Now;
                    responseResult.Success = ServiceFactory.AccessoriesTypeServiceInstance.UpdateEntities(entity);
                }
                else
                {
                    responseResult.Message = "该配件类型不存在或已被删除";
                }
            }
            TempData["ResponseResult"] = responseResult;
            return responseResult.Success ? RedirectToAction("AccessoriesTypeManage") : RedirectToAction("AccessoriesTypeEdit", new { id = model.ID });
        }


        #endregion

        #region 禁用/启用配件类型 + JsonResult UpdateStatus(int id, bool isAvailable)
        /// <summary>
        /// 禁用/启用配件类型
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <param name="isAvailable">启用/禁用</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult UpdateStatus(int id, bool isAvailable)
        {
            var entity = ServiceFactory.AccessoriesTypeServiceInstance.LoadByID(id);
            var success = false;
            if (entity != null)
            {

                entity.IsAvailable = isAvailable;
                entity.LastModifyBy = CurrentUser.UserAccount;
                entity.LastModifyTime = DateTime.Now;
                success = ServiceFactory.AccessoriesTypeServiceInstance.UpdateEntities(entity);
            }
            return Json(new
            {
                success = success,
                message = success ? "修改成功" : "修改失败"
            });
        }
        #endregion

        #region 获取配件类型 + JsonResult GetAccessoriesType(int productTypeId,string Ids)
        public JsonResult GetAccessoriesType(int productTypeId, string Ids)
        {
            //需要排除掉的配件类型
            List<int> ids = new List<int>();
            if (!string.IsNullOrEmpty(Ids))
                ids = Ids.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(Int32.Parse).ToList();

            var entities = ServiceFactory.AccessoriesTypeServiceInstance.LoadEntities(o => o.ProductTypeID == productTypeId && o.IsAvailable == true && !ids.Contains(o.ID)).Select(t => new
            {
                t.ID,
                t.AccessoriesName
            }).AsNoTracking().ToList();
            return Json(new { Result = true, Data = entities }, JsonRequestBehavior.AllowGet);
        }
        #endregion
    }
}